<?php

namespace app\master\controller;

class User extends PublicController
{

    /**
     * 登陆
     */
    public function login()
    {
        $this->view->engine->layout(false);
        if (!request()->isPost()) {
            session(null);
            return $this->fetch('login');
        }
        //接受数据
        $data['username'] = input('post.username');
        $data['password'] = md5(input('post.password'));
        $data['captcha'] = input('post.captcha');
        //校验数据
        $validate = validate('admin');
        if (!$validate->scene('login')->check($data)) {
            $this->error($validate->getError());
        }
        unset($data['captcha']);
        //查询数据
        $adminModel = model('admin');
        $admin = $adminModel::get($data);

        // 判断是否有该用户
        if (!$admin) {
            $this->error('用户名或密码错误');
        }
        if ($admin['status'] != 1) {
            $this->error('账户异常，请联系客服！');
        }
        // 将用户信息存入缓存
        session('admin_id', $admin->admin_id);
        session('admin_name', $admin->username);
        session('is_store', $admin->is_store);
        $arr = db('permission')->column('permission_id');
        session("permission", $arr);
        // 为用户记录登陆时间
        $admin->last_login_time = time();
        $admin->save();
        //登录成功

        //        //查询用户权限并存入缓存
        $role = db('admin_role')->where(['admin_id' => $admin->admin_id])->find();
        session('role_id', $role['role_id']);
        $id = db('role_permission')->where(['role_id' => $role['role_id']])->find();
        $urlOld = db('permission')->where(['permission_id' => $id["permission_id"]])->order('order_number desc')->find();

        if (!$urlOld["rule"]) {
            $urlOld = db('permission')->where(['pid' => $urlOld["permission_id"], "status" => 1])->order('order_number desc')->find();
        }
        $arr = db('role_permission')->where(['role_id' => session('role_id')])->column('permission_id');
        session("permission", $arr);

        if (in_array(config('INDEX_PERID'), $arr)) {
            $urlOld = db('Permission')->find(config('INDEX_PERID'));
        }

        //登录成功
//        $url = urldecode(input('url'));
//        if (!$url) {
        $url = $urlOld["rule"];
//        }
        $this->success('登录成功', $url);

    }

    /**
     * 退出登录
     */
    public function logout()
    {
        $this->view->engine->layout(false);
        session("admin_id", null);
        $this->redirect('User/login');
    }
}